// src/components/message-list.tsx
import React, {useEffect, useState} from 'react';
import {Member, Message as MessageType} from "@/lib/social/types";
import {differenceInMinutes, format, formatDate, isToday, isYesterday} from 'date-fns'
import Message from '@/components/social/message'
import ChannelHero from "@/components/social/channel-hero";
import {useWorkspaceId} from "@/hooks/social/use-workspace-id";
import {useCurrentMember} from "@/features/workspaces/api/use-current-member";
import {Loader} from "lucide-react";
import {Button} from "@/components/ui/button";
import ConversationHero from "@/components/social/conversation-hero";
import {formatDateLabel} from "@/lib/utils";
import {useCurrentUser} from "@/hooks/use-current-user";

// 消息紧缩的时间阈值(5min内的同一个人的消息样式收紧)
const TIME_THRESHOLD = 5

interface Props {
    memberName?: string
    memberImage?: string
    channelName?: string
    channelCreationTime?: number
    variant?: "channel" | "thread" | "conversation"
    data: MessageType[] | undefined
    loadMore: (page: number) => Promise<unknown>
    isLoadingMore: boolean
    canLoadMore: boolean
}

const MessageList = ({
                         memberName, memberImage, channelName, channelCreationTime, data,
                         variant = 'channel', loadMore, isLoadingMore, canLoadMore: canMore
                     }: Props) => {
    console.log('message list', data)

    const user = useCurrentUser()

    const [page, setPage] = useState(2)

    const [editingId, setEditingId] = useState<string | null>(null);

    const workspaceId = useWorkspaceId()
    const [member, setMember] = useState<Member | null>(null);

    const [defaultData, setDefaultData] = useState(data)
    const [canLoadMore, setCanLoadMore] = useState(true)

    useEffect(() => {
        (async () => {
            const {data} = await useCurrentMember({
                workspaceId, userId: user?.id!
            })
            setMember(data)
        })()
    }, []);

    const [groupedMessages, setGroupedMessages] = useState();
    useEffect(() => {
        // 根据哪一天进行分组
        // const groupedMessages = data?.reduce(
        const messages = defaultData?.reduce(
            (groups, message) => {
                const date = new Date(message.createdAt!)
                const dateKey = format(date, 'yyyy-MM-dd')
                if (!groups[dateKey]) {
                    groups[dateKey] = []
                }
                // unshift 从尾部添加
                groups[dateKey].unshift(message)
                return groups
            },
            // ['2024-01-01', {1,2,3,4,...}]
            {} as Record<string, typeof data>
        )
        // @ts-ignore
        setGroupedMessages(messages)
    }, [defaultData, data])

    // if (!defaultData || !data || !groupedMessages) return <div>loading...</div>

    return (
        <div className={`flex flex-1 flex-col-reverse pb-4 overflow-y-auto messages-scrollbar`}>
            {Object.entries(groupedMessages || {}).map(([dateKey, messages]) => (
                <div key={dateKey}>
                    <div className={`text-center my-2 relative`}>
                        <hr className={`absolute top-1/2 left-0 right-0 border-t border-gray-300`}/>
                        <span className={`relative inline-block bg-white px-4 py-1 rounded-full text-xs
                        border border-gray-300 shadow-sm`}>
                            {formatDateLabel(dateKey)}
                        </span>
                    </div>
                    {/*@ts-ignore*/}
                    {messages.map((message, index) => {
                            console.log('message list map message: ', message)
                            // @ts-ignore
                            const prevMessage = messages[index - 1]
                            const isCompact =
                                /*
                                prevMessage && prevMessage.user?.id === message.user?.id
                                && differenceInMinutes( // 相差不超过5分钟
                                new Date(message.createdAt),
                                new Date(prevMessage.createdAt),
                                ) < TIME_THRESHOLD
                                */
                                prevMessage && prevMessage.member.user?.id === message.member.user?.id
                                && differenceInMinutes( // 相差不超过5分钟
                                    new Date(message.createdAt!),
                                    new Date(prevMessage.createdAt!),
                                ) < TIME_THRESHOLD


                            return <Message
                                key={message.id}
                                id={message.id}
                                memberId={message.memberId}
                                // memberId={'malred'}
                                authorImage={message.member.user.image}
                                authorName={message.member.user.name}
                                // authorImage={'https://picsum.photos/200'}
                                // authorName={'malred'}
                                isAuthor={message.memberId === member?.id}
                                reactions={message.relation! || []}
                                body={message.body}
                                image={message.image}
                                updatedAt={message.updatedAt!}
                                createdAt={message.createdAt!}
                                isEditing={editingId === message.id}
                                setEditingId={setEditingId}
                                isCompact={isCompact}
                                hideThreadButton={variant === 'thread'}
                                threadCount={message.threadCount}
                                threadImage={message.threadImage}
                                threadTimestamp={parseInt(message.threadTimestamp)}
                                // threadName={message.threadName}
                            />
                        }
                    )}
                </div>
            ))}
            <div className={`w-full h-16 flex items-center justify-center`}>
                <Button
                    size={'sm'}
                    variant={'outline'}
                    className={``}
                    onClick={() => {
                        loadMore(page).then((data) => {
                            // @ts-ignore
                            if (page <= data.pages) {
                                setDefaultData([
                                    // @ts-ignore
                                    ...defaultData,
                                    // @ts-ignore
                                    // ...data.data
                                    ...data
                                ])
                                setPage((prev) => prev + 1)
                            } else {
                                setCanLoadMore(false)
                            }
                        })
                    }}
                    disabled={!canLoadMore}
                >
                    {canLoadMore ? 'Load More' : 'No More'}
                </Button>
            </div>
            {/*<div className={`h-1`}*/}
            {/*     ref={(el) => {*/}
            {/*         if (el) {*/}
            {/*             // 检测是否进入视口*/}
            {/*             const observer = new IntersectionObserver(*/}
            {/*                 ([entry]) => {*/}
            {/*                     if (entry.isIntersecting && canLoadMore) {*/}
            {/*                         loadMore(page).then((data) => {*/}
            {/*                             console.log(1)*/}
            {/*                             // console.log(data)*/}
            {/*                             if (page <= data.pages) {*/}
            {/*                                 setDefaultData(data.data)*/}
            {/*                                 setDefaultData([*/}
            {/*                                     ...defaultData,*/}
            {/*                                     ...data.data*/}
            {/*                                 ])*/}
            {/*                                 setPage((prev) => prev + 1)*/}
            {/*                             }*/}
            {/*                         })*/}
            {/*                     }*/}
            {/*                 },*/}
            {/*                 {threshold: 1.0}*/}
            {/*             )*/}

            {/*             observer.observe(el)*/}
            {/*             return () => observer.disconnect()*/}
            {/*         }*/}
            {/*     }}*/}
            {/*/>*/}
            {isLoadingMore && (
                <div className={`text-center my-2 relative`}>
                    <hr className={`absolute top-1/2 left-0 right-0 border-t border-gray-300`}/>
                    <span className={`relative inline-block bg-white px-4 py-1 rounded-full text-xs
                        border border-gray-300 shadow-sm`}>
                           <Loader className={`size-4 animate-spin`}/>
                        </span>
                </div>
            )}
            {variant === 'channel' && channelName && channelCreationTime && (
                <ChannelHero
                    name={channelName}
                    creationTime={channelCreationTime}
                />
            )}
            {variant === 'conversation' && memberName && memberImage && (
                <ConversationHero
                    name={memberName}
                    image={memberImage}
                />
            )}
        </div>
    );
};

export default MessageList;